package com.zhugang.week05;

/**
 * @program algorithms
 * @description: bSearch
 * @author: chanzhugang
 * @create: 2022/07/04 00:27
 */
public class BSearch2 {

    public static void main(String[] args) {
        BSearch2 bSearch2 = new BSearch2();
        int[] a = new int[]{1, 2, 3, 4, 5};
        int index = bSearch2.bSearch(a, a.length, 3);
        System.out.println(index);
    }

    /**
     * 二分查找（递归实现）
     *
     * @param a
     * @param n
     * @param value
     * @return
     */
    public int bSearch(int[] a, int n, int value) {
        return bSearch_r(a, 0, n - 1, value);
    }

    private int bSearch_r(int[] a, int low, int high, int value) {
        if (low > high) {
            return -1;
        }
        int mid = (low + high) / 2;
        if (a[mid] == value) {
            return mid;
        } else if (a[mid] < value) {
            return bSearch_r(a, mid + 1, high, value);
        } else {
            return bSearch_r(a, low, mid - 1, value);
        }
    }
}